﻿using Domain.Entity;
using Domain.Event;
using Domain.ValueObject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    /// <summary>
    /// 领域层服务
    /// </summary>
    public class UserDomainService
    {
        private readonly IUserDomainRepository repository;
        private readonly ISmsCodeSender smsSend;

        public UserDomainService(IUserDomainRepository repository, ISmsCodeSender smsSend)
        {
            this.repository = repository;
            this.smsSend = smsSend;
        }

        public bool IsLockOut(User user)
        {
            return user.AccessFail.IsLockOut();
        }

        public void ResetAccessFail(User user)
        {
            user.AccessFail.Reset();
        }

        public void AccessFail(User user)
        {
            user.AccessFail.InvokeFail();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<UserAccessResult> CheckLoginAsync(PhoneNumber phone, string pwd)
        {
            User? user = await repository.FindOneAsync(phone);
            UserAccessResult result;
            if (null == user) return UserAccessResult.PhoneNumberNotFound;
            else if (IsLockOut(user)) result = UserAccessResult.Lockout;
            else if (!user.HasPassword()) result = UserAccessResult.NoPassword;
            else if (user.CheckPassword(pwd)) result = UserAccessResult.OK;
            else result = UserAccessResult.PasswordError;

            if (null != user && result == UserAccessResult.OK) ResetAccessFail(user);
            else AccessFail(user);

            UserAccessResultEvent even = new(phone, result); //发布事件
            await repository.PublishEventAsync(even);
            return result;
        }

        /// <summary>
        /// 检测 验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<CheckCodeResult> CheckCodeAsynce(PhoneNumber phone, string code) 
        {
            User? user= await repository.FindOneAsync(phone);
            if (null == user) return CheckCodeResult.PhoneNumberNotFound;
            if (IsLockOut(user)) return CheckCodeResult.Lockout;
            string? codeInfo= await repository.GetCodeByPhoneAsync(phone);
            if (!string.IsNullOrEmpty(codeInfo)) return CheckCodeResult.OK;
            AccessFail(user);
            return CheckCodeResult.CodeError;
        }
    }
}
